/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */
import { OhosLogger } from '../utils/log/ohos-logger.js';

export interface pathParamsOpt {
  // parameterFile对应的路径，用于报错
  parameterFilePath?: string;

  // ohPackageFile对应的路径，用于报错
  ohPackageFilePath: string;
}

export interface tagValidateParamsOpt extends pathParamsOpt {
  // parameterFile中的key
  key: string;

  // parameterFile中的value
  value: string;

  // @param关键字替换依赖的名称，用于判断是否为version
  dependencyName?: string;
}

const TAG_REG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,59}$/;

const _log: OhosLogger = OhosLogger.getLogger('TagValidate');

/**
 * 新增tag相关校验,如果tag配置在version则直接报错,如果不符合tag规则则返回false不进行校验
 *
 * @param tagValidateParams
 */
export function isValidateTag(tagValidateParams: tagValidateParamsOpt) {
  const { key, value, parameterFilePath, ohPackageFilePath, dependencyName } = tagValidateParams;
  if (!value.startsWith('tag:')) {
    return false;
  }
  if (!TAG_REG.test(value.split('tag:')[1])) {
    _log.printErrorExit('INVALID_TAG_%S_AT_%S', [value.split('tag:')[1], parameterFilePath], [[value.split('tag:')[1], key, parameterFilePath]]);
  }
  if (dependencyName === 'version') {
    _log.printErrorExit('THE_TAG_KEYWORD_IS_NOT_ALLOWED_FOR_VERSION_AT_%S', [ohPackageFilePath], [[value, key, parameterFilePath]]);
  }
  return true;
}
